<?php

// +----------------------------------------------------------------------
// | ADMEXPRESS [ 国际领先的转运系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 扬州安蝶梦电子商务有限公司 All rights reserved.
// +----------------------------------------------------------------------
// | Author: 曹梦龙 <138888611@qq.com> <http://www.andiemeng.com>
// +----------------------------------------------------------------------

namespace Home\Controller;

use Think\Controller;

class CenterController extends HomeController {

    //包裹首页
    public function index() {
        
        $type = I('type');
        if (!$type) {
            $type = -1;
            $map['status'] = array('in', '1000,2000,0');
        }
        if ($type == -1) {
            $map['status'] = array('in', '1000,2000,0');
        };
        $this->type = $type;

        if ($type > -1) {
            $map['status'] = $type;
        }

        if ($type == 10) {
            $map['status'] = 0;
        }

        $uid = session('user_auth.uid');
        $map['uid'] = $uid;

        $packagecount = M('package')->where(array('uid' => $uid))->Count();
        //  dump($packagecount);
        $this->packagecount = $packagecount;

        $this->uid = $uid;
        $list = M('Package')->where($map)->order('id desc')->select();
        int_to_string_package($list);
        $this->assign('_list', $list);
        $this->meta_title = '仓库包裹信息';
        
        $this->nvazhi=1;
        $this->display();
    }

    //订单详情
    public function details() {
        $oid = I('oid');
        //dump($oid);
        $map['id'] = $oid;
        $data = D('OrdersView')->where($map)->find();

        $data['packages'] = M('package')->where(array('oid' => $oid))->select();
        $data['eline'] = M('Expressline')->where(array('id' => $data['eid']))->find();
        $mapl['fid'] = $oid;
        $mapl['tpye'] = 1;
        $data['logs'] = D('logs')->where($mapl)->select();
        $data['status_text'] = D('logs')->where($mapl)->order('id desc')->find();
        $this->data = $data;
        //dump($data);
        $this->nvazhi=3;
        $this->display();
    }

    //财务流水账
    public function accountdetail() {
        $uid = session('user_auth.uid');
        $map['uid'] = $uid;
        $data = D('member_paymentdetail')->where($map)->order('id desc')->select();
        $this->data = $data;
        $map['mold'] = 2;
        $zhichu = D('member_paymentdetail')->where($map)->Sum("money");
        $this->zhichu = $zhichu;
        $map['mold'] = 1;
        $shouru = D('member_paymentdetail')->where($map)->Sum("money");       
        $this->shouru = number_format($shouru,2);
        $this->nvazhi=4;
        $this->display();
    }

    //仓库地址
    public function warehouse() {
        $cdatalist = D('common_country')->where(array('status' => 1))->select();
        $cid = I('CID');
        if ($cid < 0) {
            $wdatalist = D('warehouse')->where(array('status' => 1))->select();
            $this->active = -1;
        } else {
            $wdatalist = D('warehouse')->where(array('status' => 1, 'country_id' => $cid))->select();
            $this->active = $cid;
        }
        $uid = session('user_auth.uid');



        foreach ($wdatalist AS $k => $v) {
            $map['uid'] = $uid;
            $map['wid'] = $wdatalist[$k]['id'];
            $map['status'] = array('not in', '6000,7000,0');
            $wdatalist[$k]['countpackages'] = M('package')->where($map)->count();
            $map['status'] = 0;
            $wdatalist[$k]['countwillarraivepackages'] = M('package')->where($map)->count();
        }

        $this->clist = $cdatalist;
        $this->wlist = $wdatalist;
        $this->nvazhi=2;
        $this->display();
    }

    //包裹预约入库
    public function packageadd($WID = '') {
        if (IS_POST) {
            if (!checkToken($_POST['TOKEN'])) {
                $this->error("请勿重复提交表单.", U('Center/warehouse', 'CID=-1'));
            }
            $warehouse_id = I('warehouse_id');
            $warehouse_name = I('warehouse_name');
            $package_name = I('package_name');
            $forecast_exp_name = I('forecast_exp_name');
            $forecast_exp_number = I('forecast_exp_number');
            $package_price = I('package_price');
            $package_caption = I('package_caption');
            $uid = session('user_auth.uid');
            $username = session('user_auth.username');
            $package = array('name' => $package_name, 'remark' => $package_caption, 'price' => $package_price, 'uid' => $uid, 'wid' => $warehouse_id, 'username' => $username, 'expressname' => $forecast_exp_name, 'expressnumber' => $forecast_exp_number, 'mold' => 0, 'status' => 0, 'createdate' => NOW_TIME);
            $fid = M('package')->add($package);
            if (!$fid) {
                $this->error("包裹预报添加失败！");
            } else {
                $log = array('fid' => $fid, 'tpye' => 0, 'info' => '0', 'remark' => '创建了包裹《' . $package_name . "》", 'username' => $username, 'createdate' => NOW_TIME);
                M('logs')->add($log);
                $this->success('包裹预报成功！', U('Center/warehouse', 'CID=-1'));
            }
        } else {
            creatToken();
            $warehousedata = D('warehouse')->where(array('id' => $WID))->find();
            $this->vo = $warehousedata;
            $this->nvazhi=1;
            $this->display();
        }
    }

    //包裹查看
    public function package($WID = '') {
        $type = I('type');
        if (!$type) {
            $type = -1;
        }
        if ($type >= 0) {
            $map['status'] = $type;
        }

        if ($map['status'] == "10") {
            $map['status'] = 0;
        }

        $this->type = $type;
        $this->wid = $WID;



        $uid = session('user_auth.uid');
        $map['uid'] = $uid;
        $map['wid'] = I('WID');


        $list = M('Package')->where($map)->order('id desc')->select();
        int_to_string_package($list);

        $this->assign('_list', $list);
        $this->meta_title = '仓库包裹信息';
        $this->nvazhi=2;
        $this->display();
    }

    //我的地址列表
    public function myaddress() {
        $countrylist = M('common_country')->select();
        $this->countrylist = $countrylist;
        $map['uid'] = session('user_auth.uid');
        $addresslist = M('member_address')->where($map)->select();
        $this->addresslist = $addresslist;
        $this->nvazhi=4;
        $this->display();
    }

    //我的地址添加
    public function myaddressadd($countryid = "", $name = "", $country = "", $province = "", $city = "", $location = "", $zipcode = "", $phone = "") {
        $address = array('uid' => session('user_auth.uid'), 'countryid' => $countryid, 'name' => $name, 'country' => $country, 'province' => $province, 'city' => $city, 'location' => $location, 'zipcode' => $zipcode, 'phone' => $phone);
        if (!M('member_address')->add($address)) {
            $this->error("用户地址添加失败！");
        } else {
            $this->success('用户地址添加成功！', U('myaddress'));
        }
        
    }

    //我的地址修改
    public function myaddressedit($countryid = "", $name = "", $country = "", $province = "", $city = "", $location = "", $zipcode = "", $phone = "") {
        $map['id'] = I('id');
        $map['uid'] = session('user_auth.uid');
        if (IS_POST) {
            $address = array('countryid' => $countryid, 'name' => $name, 'country' => $country, 'province' => $province, 'city' => $city, 'location' => $location, 'zipcode' => $zipcode, 'phone' => $phone);
            if (!D('member_address')->where($map)->save($address)) {
                dump($map);
                $this->error("用户地址修改失败！");
            } else {
                $this->success('用户地址修改成功！', U('myaddress'));
            }
        } else {
            $countrylist = M('common_country')->select();
            $this->countrylist = $countrylist;
            $address = M('member_address')->where($map)->find();
            $this->address = $address;
            $this->nvazhi=4;
            $this->display();
        }
    }

    //我的地址删除
    public function myaddressdel() {
        $map['id'] = I('id');
        $map['uid'] = session('user_auth.uid');
        if (!D('member_address')->where($map)->delete()) {
            $this->error("用户地址删除失败！");
        } else {
            $this->success('用户地址删除成功！', U('myaddress'));
        }
    }

    //订单生成
    public function ordercreate() {
        if (IS_POST) {
            //显示需要打包的包裹    
            $pid = I('pid');
            $wid = I('wid');
            if (!$pid) {
                $this->error("请先选择包裹再进行转运申请！");
            }
            if (!$wid) {
                $this->error('非法访问！', U('index'));
            }
            $this->pid = $pid;
            $this->wid = $wid;
            session('pid', $pid);
            $uid = session('user_auth.uid');
            $map['uid'] = $uid;
            $map['id'] = array('in', $pid);

            $list = M('Package')->where($map)->select();
            $weightcount = 0;
            foreach ($list as $key => $value) {

                if ($list[$key]['weight'] < $list[$key]['bulkfactor']) {
                    $weightcount = $weightcount + $list[$key]['bulkfactor'];
                } else {
                    $weightcount = $weightcount + $list[$key]['weight'];
                }
            }


            int_to_string_package($list);
            $this->assign('_list', $list);
            //显示收货地址选择
            $map2['uid'] = session('user_auth.uid');
            $addresslist = M('member_address')->where($map2)->select();
            $this->addresslist = $addresslist;
            //显示物流信息选择
            $listExpline = M('Expressline')->where($map3)->select();

            foreach ($listExpline as $key => $value) {

                if ($weightcount < $listExpline[$key]['fweight']) {
                    //小于首重
                    $money = $listExpline[$key]['fprice'];
                } else {
                    //运费计算
                    $money = $listExpline[$key]['fprice'] + ($weightcount - $listExpline[$key]['fweight']) / $listExpline[$key]['cweight'] * $listExpline[$key]['cprice'];
                }

                $listExpline[$key]['willpice'] = $money;
            }


            $this->assign('_listExpline', $listExpline);
            $this->nvazhi=3;
            $this->display();
        }
    }

    public function ordercreateaction() {
        if (IS_POST) {
            $pid = session('pid');
            $aid = I('aid');
            $eid = I('eid');
            $wid = I('wid');
            if (!$aid || !$eid) {
                $this->error("参数不正确非法提交", U('index'));
            }

            $uid = session('user_auth.uid');
            //创建ORDER记录
            $order = array('uid' => $uid, 'type' => 0, 'createdate' => NOW_TIME, 'status' => 3000);
            $oid = M('orders')->add($order);
            if (!$oid) {
                $this->error("订单创建失败！");
            }
            //创建ORDER_detailexpress记录
            $Adata = M('member_address')->where(array('id' => $aid))->find();
            $orderdetailexpress = array('oid' => $oid, 'eid' => $eid, 'wid' => $wid, 'countryid' => $Adata['countryid'], 'name' => $Adata['name'], 'country' => $Adata['country'], 'province' => $Adata['province'], 'city' => $Adata['city'], 'address' => $Adata['location'], 'zipcode' => $Adata['zipcode'], 'phone' => $Adata['phone'], 'remark' => I('remark'), 'createdate' => NOW_TIME);
            $oeid = M('orders_detailexpress')->add($orderdetailexpress);
            if (!$oeid) {
                $this->error("订单创建失败！");
            }
            $username = session('user_auth.username');

            $log = array('fid' => $oid, 'tpye' => 1, 'info' => '3000', 'remark' => '创建了订单,等待打包称重计费。', 'username' => $username, 'createdate' => NOW_TIME);
            M('logs')->add($log);

            //修改包裹状态以及
            $data['status'] = 3000;
            $data['oid'] = $oid;
            $map['id'] = array('in', $pid);
            M('Package')->where($map)->save($data);
            //添加记录

            $num = count($pid);
            for ($i = 0; $i < $num; ++$i) {
                $log = array('fid' => $pid[$i], 'tpye' => 0, 'info' => '3000', 'remark' => '包裹申请出库，等待出库打包，称重，计算费用。对应订单ID:' . $oid, 'username' => $username, 'createdate' => NOW_TIME);
                M('logs')->add($log);
            }
            $this->success('出库申请提交成功，请等待付款通知！', U('Center/order'));
        }
    }

    //订单查看
    public function order() {
        $type = I('type');
        if (!$type) {
            $type = -1;
        }
        $this->type = $type;
        if ($type > -1) {
            $map['status'] = $type;
        }




        $uid = session('user_auth.uid');
        $map['uid'] = $uid;
        $list = D('OrdersView')->where($map)->order('id desc')->select();
        int_to_string_package($list);
        foreach ($list AS $k => $v) {
            $list[$k]['packages'] = M('package')->where(array('oid' => $v['id']))->select();
        }
        $this->assign('_list', $list);
        $this->meta_title = '订单信息';
$this->nvazhi=3;
        $this->display();
    }

    //订单支付
    public function pay($oid) {
        $map['id'] = $oid;
        $list = D('OrdersView')->where($map)->find();
        int_to_string_package($list);
        $list['packages'] = M('package')->where(array('oid' => $list['id']))->select();
        creatToken();
        $this->assign('vo', $list);
        $this->nvazhi=3;
        $this->display();
    }

    //订单支付结算
    public function payaction() {
        if (IS_POST) {
            if (!checkToken($_POST['TOKEN'])) {
                $this->error("请勿重复提交表单.", U('Center/order', 'type=-1'));
            }
            $oid = I('oid');
            $uid = session('user_auth.uid');
            $map['id'] = $oid;
            $orderdata = D('OrdersView')->where($map)->find();
            $money = $orderdata['money'];
            //dump($orderdata);

            $mmap['uid'] = $uid;
            $memberdata = D('member')->where($mmap)->find();
            $balance = $memberdata['balance'];


            if ($orderdata['status'] == 4000) {
                //判断是否还未付款
                if ($money < $balance) {
                    //支付过程                
                    $result = D('member')->where($mmap)->setDec('balance', $money); // 用户的余额减少             
                    if ($result == 1) {
                        //扣款成功
                        //修改包裹状态以及
                        $data['status'] = 5000;
                        M('Package')->where(array('oid' => $oid))->save($data);
                        M('Orders')->where(array('id' => $oid))->save($data);
                        $username = session('user_auth.username');
                        $nowbalance = $balance - $money;
                        $paymentdetail = array('uid' => $uid, 'mold' => 2, 'money' => $money, 'createdate' => NOW_TIME, 'remark' => "[消费]对订单" . $oid . "进行了付款", 'operator' => $username, 'balance' => $nowbalance);
                        M('member_paymentdetail')->add($paymentdetail);


                        $log = array('fid' => $oid, 'tpye' => 1, 'info' => '5000', 'remark' => '订单已经付款，下一步开始发货，请耐心等待。', 'username' => $username, 'createdate' => NOW_TIME);
                        M('logs')->add($log);


                        $this->success("订单支付成功！我们会尽快为您发货，请留意订单状态！", U('Center/order', 'type=-1'));
                    }
                } else {
                    //钱不够报错
                    $this->error("您的账户余额不足以支付本订单！请您充值~.", U('Center/order', 'type=-1'));
                }
            } else {
                $this->error('改订单无法进行支付！', U('Center/order', 'type=-1'));
            }
        } else {
            $this->error('非法访问', U('Center/order', 'type=-1'));
        }
    }

    //确认收货显示
    public function signin($oid) {
        $map['id'] = $oid;
        $list = D('OrdersView')->where($map)->find();
        int_to_string_package($list);
        $list['packages'] = M('package')->where(array('oid' => $list['id']))->select();
        creatToken();
        $this->assign('vo', $list);
        $this->nvazhi=3;
        $this->display();
    }

    //订单支付结算
    public function signinaction() {
        if (IS_POST) {
            if (!checkToken($_POST['TOKEN'])) {
                $this->error("请勿重复提交表单.", U('Center/order', 'type=-1'));
            }
        }
        $oid = I('oid');
        $uid = session('user_auth.uid');
        $map['id'] = $oid;
        $orderdata = D('OrdersView')->where($map)->find();
        if ($orderdata['status'] == 6000) {
            //判读已经发货
            $data['status'] = 7000;
            M('Package')->where(array('oid' => $oid))->save($data);
            M('Orders')->where(array('id' => $oid))->save($data);
            $username = session('user_auth.username');
            $log = array('fid' => $oid, 'tpye' => 1, 'info' => '7000', 'remark' => '订单已确认收货，欢迎再次光临！', 'username' => $username, 'createdate' => NOW_TIME);
            M('logs')->add($log);
            $this->success("本次转运全部完成！共享您成为优质客户，我们将会继续为您服务！", U('Center/order', 'type=-1'));
        } else {
            $this->error('非法访问', U('Center/order', 'type=-1'));
        }
    }
    
   
    

}
